import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'
import { appoxEnums } from '@/appox/appox'
import { agencyAsync } from '@/appox/appox'
import { appoxCallback } from '@/appox/appox'

export const useGenerationSettingStore = defineStore('generationSetting', () => {
  // 状态
  const dialogQueue = new DialogQueue()
  const generationList = ref([])
  const inputGeneration = ref('')
  const outputGeneration = ref('')
  const showOutputGeneration = ref(false)

  // 动作
  async function initialize() {
    const appMode = await agencyAsync.getAppMode()
    
    if (appMode === appoxEnums.ApplicationMode.Offline) {
      showOutputGeneration.value = true
      const offlineOutputGenID = await agencyAsync.getGlobalParameter('System.OfflineOutputGenID', null)
      outputGeneration.value = offlineOutputGenID == null || offlineOutputGenID.length === 0 ? 'default' : offlineOutputGenID
      
      const inputGenID = await agencyAsync.getGlobalParameter('System.OfflineInputGenID', null)
      inputGeneration.value = inputGenID == null || inputGenID.length === 0 ? '' : inputGenID
    } else {
      showOutputGeneration.value = false
      outputGeneration.value = ''
      
      if (appMode === appoxEnums.ApplicationMode.Replay) {
        const inputGenID = await agencyAsync.getGlobalParameter('System.ReplayGenerationID', null)
        inputGeneration.value = inputGenID == null || inputGenID.length === 0 ? '' : inputGenID
      }
    }

    generationList.value = await agencyAsync.getGenerationList()
  }

  async function handleInputGenerationChange(value) {
    inputGeneration.value = value
    const appMode = await agencyAsync.getAppMode()
    const parameter = appMode === appoxEnums.ApplicationMode.Offline 
      ? 'System.OfflineInputGenID'
      : 'System.ReplayGenerationID'
    await agencyAsync.setGlobalParameter(parameter, value)
  }

  async function handleOutputGenerationChange(value) {
    outputGeneration.value = value || 'default'
    await agencyAsync.setGlobalParameter('System.OfflineOutputGenID', outputGeneration.value)
  }

  function show() {
    return dialogQueue.show({
      onLoaded: () => initialize()
    })
  }

  function hide() {
    dialogQueue.hide()
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    generationList,
    inputGeneration,
    outputGeneration,
    showOutputGeneration,
    // 动作
    initialize,
    handleInputGenerationChange,
    handleOutputGenerationChange,
    show,
    hide,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
}) 